# -*- mode: org; fill-column: 80; -*-
#+TITLE: Prompt
#+SUBTITLE: PS1 code
#+AUTHOR: Zelphir Kaltstahl
#+STARTUP: content
#+STARTUP: indent
#+STARTUP: align
#+STARTUP: shrink
#+STARTUP: inlineimages
#+STARTUP: entitiesplain
#+STARTUP: nologdone
#+STARTUP: nologreschedule
#+STARTUP: nologredeadline
#+STARTUP: nologrefile
#+STARTUP: hidestars
#+STARTUP: oddeven
#+TODO: TODO WIP | DONE
#+DATE: [2023-05-21 So]
#+LANGUAGE: English
#+PRIORITIES: A C C
#+EXCLUDE_TAGS: noexport
#+KEYWORDS: bash prompt terminal

* Abbreviated current working directory

The following PS1 code will result in a prompt with abbreviated current working directory:

#+begin_src bash
##########
# PROMPT #
##########
function nonzero_return() {
    RETVAL="${?}"
    # printf "RETVAL is: %s\n" "${?}"
    if [ ${RETVAL} -ne 0 ]; then
        RESULT="\[$(tput setaf 196)\][${RETVAL}]\[$(tput sgr0)\]"
        printf ${RESULT@P}
    else
        printf "[0]"
    fi
}

function abbreviate() {
    MAX_LEN="${2}"
    STR_LEN="${#1}"
    STR="${1}"
    if [ "${STR_LEN}" -gt "${MAX_LEN}" ]; then
        START_POS=$((${STR_LEN}-${MAX_LEN}))
        echo "...${STR:${START_POS}}"
    else
        echo "${STR}"
    fi
}

PS1_USER="\u"
PS1_USER_STYLED="\[$(tput setaf 39)\]${PS1_USER}\[$(tput sgr0)\]"

PS1_HOST="\h"
PS1_HOST_STYLED="\[$(tput setaf 10)\]${PS1_HOST}\[$(tput sgr0)\]"

CURRENT_DIR_MAX_LEN=20

# We need to escape subshell calls and subshell calls inside subshell
# calls using '\$(...)' to avoid too early evaluation. If the
# subshells were evaluated when the .bashrc file is read, the results
# would never change, no matter whether we switch directory later.

# Furthermore the nonzero_return call needs to be before other
# function calls, otherwise the last exit code will be overwritten by
# the exit codes of those function calls.

# Also we should not forget to wrap the later evaluated call of
# \$(pwd) in escaped quotes, so that filenames including spaces are
# handled correctly.
export PS1="${PS1_USER_STYLED}@${PS1_HOST_STYLED}:\$(nonzero_return):\[$(tput setaf 203)\]\$(abbreviate \"\$(pwd)\" ${CURRENT_DIR_MAX_LEN})\[$(tput sgr0)\]\\$ "
#+end_src
